package com.baizhi.service.impl;

import com.baizhi.dao.HeroDao;
import com.baizhi.entity.Hero;
import com.baizhi.service.HeroService;
import com.baizhi.util.MybatisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class HeroServiceImpl implements HeroService {
    @Override
    public PageInfo selectByPage(int pageNo, int pageSize) {
        SqlSession session = null;
        PageHelper.startPage(pageNo,pageSize);
        List<Hero> heroes = null;
        try {
            session = MybatisUtil.getSqlSession();
            HeroDao dao = session.getMapper(HeroDao.class);
            heroes = dao.selectAll();
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
        return new PageInfo(heroes);
    }

    @Override
    public void delete(int id) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            HeroDao dao = session.getMapper(HeroDao.class);
            dao.delete(id);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }

    @Override
    public void update(Hero hero) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            HeroDao dao = session.getMapper(HeroDao.class);
            dao.update(hero);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }

    @Override
    public Hero selectOne(int id) {
        SqlSession session = null;
        Hero hero = null;
        try {
            session = MybatisUtil.getSqlSession();
            HeroDao dao = session.getMapper(HeroDao.class);
            hero = dao.selectOne(id);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
        return hero;
    }

    @Override
    public void add(Hero hero) {
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            HeroDao dao = session.getMapper(HeroDao.class);
            dao.insert(hero);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.closeSqlSession(session);
        }
    }
}
